package com.tm.service.impl;

import com.tm.enums.ResultEnum;
import com.tm.mapper.UserMapper;
import com.tm.pojo.dto.LoginDto;
import com.tm.pojo.vo.UserVo;
import com.tm.result.Result;
import com.tm.service.UserService;
import com.tm.utils.SendSmsUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaobai
 * @create 2022-12-17 21:33
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    //用户登录
    public Result userLogin(LoginDto loginDto) {

        if(StringUtils.isNotBlank(loginDto.getUserName() )  && StringUtils.isNotBlank(loginDto.getUserPwd() )) {

            UserVo userVo =  userMapper.queryUser1(loginDto.getUserName(),loginDto.getUserPwd());

            if(userVo != null){
                return Result.SUCCESS(resultList(userVo));
            }
            return Result.ZDY(ResultEnum.LOGON_ERROR);
        }

        if(StringUtils.isNotBlank(loginDto.getUserPhone()) && StringUtils.isNotBlank(loginDto.getUserCode())){
            // 获取redis 中的验证码
            ValueOperations opsForValue = redisTemplate.opsForValue();
            Object o = opsForValue.get("userCode_" + loginDto.getUserPhone());
            if(o != null){
                boolean equals = o.toString().equals(loginDto.getUserCode());
                if(equals){
                    UserVo userVo =  userMapper.queryUser2(loginDto.getUserPhone());
                    if(userVo != null){

                        return Result.SUCCESS( resultList(userVo));
                    }

                }
                return Result.ZDY(ResultEnum.SENDSMS_ERROR);
            }
            return Result.ZDY(ResultEnum.OVERDUE_ERROR);
        }

            return Result.ZDY(ResultEnum.ERROR_LOGON);
    }

    //发送验证码
    @Override
    public Result SendSms(String phoneNumber) {
        ValueOperations value = redisTemplate.opsForValue();
        Object o = value.get("userCode_" + phoneNumber);
        //是否重复发送验证码
        if(o != null){
            return Result.ZDYSMS(ResultEnum.SENDSMS_SUCCESS);
        }
        String s = SendSmsUtil.SendSms(phoneNumber);
        //放入redis中 3分钟失效
        value.set("userCode_"+phoneNumber,s,10l, TimeUnit.MINUTES);
        return Result.ZDYSMS(ResultEnum.SENDSMS_SUCCESS);
    }

    // 封装
    private UserVo resultList(UserVo userVo){

        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("token_"+userVo.getUserPhone(),token);
        userVo.setToken(token);
        return userVo;
    }
}
